import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import UserModel from '@/models/user';

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户信息
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查用户是否为企业负责人
    if (!user.is_company_admin) {
      return NextResponse.json(
        { error: '您不是企业负责人，无法发布招聘公告' },
        { status: 403 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const {
      title,
      description,
      requirements,
      salary_range,
      location,
      job_type,
      experience,
      education,
      company_id
    } = body;

    // 验证必填字段
    if (!title || !description || !requirements || !salary_range || !location) {
      return NextResponse.json(
        { error: '请填写所有必填字段' },
        { status: 400 }
      );
    }

    // 获取企业ID
    let companyId = company_id;
    if (!companyId) {
      try {
        // 先检查用户是否为企业管理员
        if (!user.is_company_admin) {
          // 如果不是，将用户设置为企业管理员
          const companyName = user.company || (user.username + '的公司');
          await UserModel.updateCompanyInfo(userId, {
            is_company_admin: true,
            company: companyName,
            company_role: '管理员'
          });

          // 更新用户对象
          user.is_company_admin = true;
          user.company = companyName;
        }

        // 查询用户关联的企业
        const [companies] = await UserModel.query<any[]>(
          `SELECT id FROM companies WHERE admin_user_id = ? OR name = ? LIMIT 1`,
          [userId, user.company]
        );

        if (companies && Array.isArray(companies) && companies.length > 0 && companies[0]?.id) {
          companyId = companies[0].id;
        } else {
          // 如果没有找到企业记录，创建一个新的
          const companyName = user.company || (user.username + '的公司');
          const [result] = await UserModel.query<any>(
            `INSERT INTO companies (name, admin_user_id, created_at)
             VALUES (?, ?, NOW())`,
            [companyName, userId]
          );

          if (result && typeof result === 'object' && 'insertId' in result) {
            companyId = result.insertId;
            console.log('创建了新的企业记录，ID:', companyId);
          } else {
            throw new Error('创建企业记录失败');
          }
        }
      } catch (companyError) {
        console.error('获取企业信息失败:', companyError);
        return NextResponse.json(
          { error: '获取企业信息失败' },
          { status: 500 }
        );
      }
    }

    // 保存招聘信息
    try {
      const [result] = await UserModel.query<any>(
        `INSERT INTO job_positions
         (company_id, title, description, requirements, salary_range,
          location, job_type, experience, education, status, created_by)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          companyId,
          title,
          description,
          requirements,
          salary_range,
          location,
          job_type || '全职',
          experience || '不限',
          education || '不限',
          'active', // 默认状态为活跃
          userId
        ]
      );

      // 检查结果是否有效
      if (result && typeof result === 'object' && 'insertId' in result) {
        return NextResponse.json(
          {
            message: '招聘公告发布成功',
            job_id: result.insertId
          },
          { status: 201 }
        );
      } else {
        return NextResponse.json(
          {
            message: '招聘公告已提交，但无法获取ID',
          },
          { status: 201 }
        );
      }
    } catch (dbError) {
      console.error('保存招聘信息失败:', dbError);
      return NextResponse.json(
        { error: '保存招聘信息失败' },
        { status: 500 }
      );
    }

  } catch (error) {
    console.error('发布招聘公告错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}
